<?php

namespace app\adminapi\controller;

use app\model\PostModel;
use app\model\UsersModel;
use app\model\TopicModel;
use Webman\Http\Request;

class Post extends BaseAdminApi
{
    /**
     * 不需要登录的方法
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 不需要权限验证的方法（已登录但不验证具体权限）
     * @var array
     */
    protected $noNeedPermission = [];

    /**
     * 获取帖子列表
     */
    public function getPosts(Request $request)
    {
        $params = $request->get();
        $pageSize = $params['pageSize'] ?? 10;

        $query = PostModel::with(['user:id,nickname,avatar', 'topic:id,name']);

        // 搜索条件
        if (!empty($params['title'])) {
            $query->where('title', 'like', '%' . $params['title'] . '%');
        }

        if (!empty($params['content'])) {
            $query->where('content', 'like', '%' . $params['content'] . '%');
        }

        if (!empty($params['user_id'])) {
            $query->where('user_id', $params['user_id']);
        }

        if (!empty($params['topic_id'])) {
            $query->where('topic_id', $params['topic_id']);
        }

        if (!empty($params['type'])) {
            $query->where('type', $params['type']);
        }

        if (!empty($params['start_date'])) {
            $query->where('created_at', '>=', $params['start_date']);
        }

        if (!empty($params['end_date'])) {
            $query->where('created_at', '<=', $params['end_date'] . ' 23:59:59');
        }

        $paginate = $query->orderBy('created_at', 'desc')
            ->paginate($pageSize);

        return dataByPage($paginate);
    }

    /**
     * 获取帖子详情
     */
    public function getPostDetail(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return fail('帖子ID不能为空');
        }

        $post = PostModel::with(['user:id,nickname,avatar', 'topic:id,name'])
            ->find($id);

        if (!$post) {
            return fail('帖子不存在');
        }

        return data($post, '获取成功');
    }

    /**
     * 删除帖子
     */
    public function deletePost(Request $request)
    {
        $id = $request->post('id');
        if (empty($id)) {
            return fail('帖子ID不能为空');
        }

        $post = PostModel::find($id);
        if (!$post) {
            return fail('帖子不存在');
        }

        try {
            // 删除帖子时，需要更新圈子的帖子数量
            $topic = TopicModel::find($post->topic_id);
            if ($topic && $topic->post_num > 0) {
                $topic->decrement('post_num');
            }

            $post->delete();
            return success('删除成功');
        } catch (\Exception $e) {
            return fail('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 批量删除帖子
     */
    public function batchDeletePosts(Request $request)
    {
        $ids = $request->post('ids');
        if (empty($ids) || !is_array($ids)) {
            return fail('请选择要删除的帖子');
        }

        try {
            $posts = PostModel::whereIn('id', $ids)->get();
            
            // 统计每个圈子需要减少的帖子数量
            $topicPostCounts = [];
            foreach ($posts as $post) {
                if (!isset($topicPostCounts[$post->topic_id])) {
                    $topicPostCounts[$post->topic_id] = 0;
                }
                $topicPostCounts[$post->topic_id]++;
            }

            // 删除帖子
            PostModel::whereIn('id', $ids)->delete();

            // 更新圈子帖子数量
            foreach ($topicPostCounts as $topicId => $count) {
                $topic = TopicModel::find($topicId);
                if ($topic) {
                    $topic->decrement('post_num', $count);
                }
            }

            return success('批量删除成功');
        } catch (\Exception $e) {
            return fail('批量删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取所有圈子列表（用于筛选）
     */
    public function getTopicOptions(Request $request)
    {
        try {
            $topics = TopicModel::select('id', 'name')
                ->orderBy('name')
                ->get();

            return success('获取圈子列表成功', $topics);
        } catch (\Exception $e) {
            return fail('获取圈子列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户列表（用于筛选）
     */
    public function getUserOptions(Request $request)
    {
        try {
            $keyword = $request->get('keyword', '');
            $query = UsersModel::select('id', 'nickname', 'username');
            
            if (!empty($keyword)) {
                $query->where(function($q) use ($keyword) {
                    $q->where('nickname', 'like', '%' . $keyword . '%')
                      ->orWhere('username', 'like', '%' . $keyword . '%');
                });
            }
            
            $users = $query->limit(20)->get();

            return success('获取用户列表成功', $users);
        } catch (\Exception $e) {
            return fail('获取用户列表失败：' . $e->getMessage());
        }
    }
}